/*
 * Copyright 2008 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.asbeangen.parser.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.splink.asbeangen.templates.ITemplateClass;
import org.splink.asbeangen.templates.IWritableClass;

public class ClassFileWriter {
	private List<ITemplateClass> _clazzStack;
	private List<IWritableClass> _interfaceStack;
	private String _targetpath;

	public ClassFileWriter(String targetpath) {
		_targetpath = targetpath;
		if (_targetpath != "")
			_targetpath += "\\";
		_clazzStack = new ArrayList<ITemplateClass>();
	}

	public void addClazz(ITemplateClass clazz) {
		_clazzStack.add(clazz);
	}

	public void addInterfaces(List<IWritableClass> interfaceStack) {
		_interfaceStack = interfaceStack;
	}

	public ITemplateClass getClazzByName(String name) {
		for (int i = 0; i < _clazzStack.size(); i++) {
			if (_clazzStack.get(i).getID()
					.equals(name.substring(0, 1).toLowerCase() + name.substring(1, name.length()))) {
				return _clazzStack.get(i);
			}
		}
		return null;
	}

	public void write() {
		for (int i = 0; i < _clazzStack.size(); i++) {
			writeToFile(_clazzStack.get(i));
		}
		for (int i = 0; i < _interfaceStack.size(); i++) {
			writeToFile(_interfaceStack.get(i));
		}

		System.out.println(_clazzStack.size() + " classes");
		if (_interfaceStack.size() > 0) {
			System.out.println(_interfaceStack.size() + " interfaces");
		}
		_clazzStack = new ArrayList<ITemplateClass>();
		_interfaceStack = new ArrayList<IWritableClass>();
	}

	private void writeToFile(IWritableClass clazz) {
		String packagename = _targetpath + clazz.getPackagename().replace(".", "\\");

		packagename = packagename.replace("\\", File.separator);

		File p = new File(packagename);

		if (!p.exists()) {
			p.mkdirs();
		}

		File f = new File(packagename + File.separator + clazz.getClassname() + "." + clazz.getExtension());
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(f, false));
			writer.write(clazz.getDefinition().toCharArray());
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(f.getAbsolutePath());
	}

	public List<ITemplateClass> getClazzStack() {
		return _clazzStack;
	}
}